package com.yotoodesign.dianba.ui;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.yotoodesign.core.util.DummyTabContent;
import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.app.GlobalApplication;
import com.yotoodesign.dianba.bean.Album;
import com.yotoodesign.dianba.bean.Song;
import com.yotoodesign.dianba.custom.CustomDialog;
import com.yotoodesign.dianba.fragment.AboutFragment;
import com.yotoodesign.dianba.fragment.BaseFragment;
import com.yotoodesign.dianba.fragment.FeedbackFragment;
import com.yotoodesign.dianba.fragment.KtvDetailFragment;
import com.yotoodesign.dianba.fragment.MyFragment;
import com.yotoodesign.dianba.fragment.SingerFragment;
import com.yotoodesign.dianba.fragment.SingerSongFragment;
import com.yotoodesign.dianba.util.Constant;
import com.yotoodesign.dianba.util.DataUtils;

public class MainActivity extends FragmentActivity {
	private GlobalApplication application;
	private TabHost tabHost;
	TabWidget tabWidget; 
	
	FragmentManager fm;
	FragmentTransaction ft;
	
	int CURRENT_TAB = 0;	//当前TAB页的索引
	int pressBackCount = 0;
	
	//TAB图标
	RelativeLayout tabIndicator1,tabIndicator2,tabIndicator3,tabIndicator4,tabIndicator5;
	//要管理的各个模块
	BaseFragment homeFragment, //主页
		myFragment,//我的点歌单
		userCenterFragment,//用户中心
		searchFragment,//搜索
		ktvFragment,//本地KTV搜索
		ktvDetailFragment,//本地KTV搜索
		moreFragment,//更多
		feedbackFragment,
		aboutFragment,
		
		//首页中的几个点歌方式
		singerFragment,//歌星
		singerSongFragment,
		pyFragment,//拼音
		languageFragment,//语种
		twoSingerFragment;//情歌对唱
	
	//当前fragment
	BaseFragment currentFragment;
	
	//我的当前点歌单
	private ArrayList<Song> currentList = new ArrayList<Song>();
	//我的点歌单列表
	private ArrayList<Album> mySongList = new ArrayList<Album>();
	
	public LocationClient mLocClient;
	
	public ArrayList<Song> getCurrentList() {
		return currentList;
	}

	public void setCurrentList(ArrayList<Song> currentList) {
		this.currentList = currentList;
	}
	
	public void addSong(Song song,float x,float y){
		currentList.add(song);
		//显示添加动画
		showAddSongEffect(x,y);
	}
	
	//显示添加效果
	private void showAddSongEffect(float x,float y){
		AnimationSet as = new AnimationSet(false);
		
		final DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		
		final ImageView ivMusicFlag = (ImageView)this.findViewById(R.id.ivMusicFlag);
		ivMusicFlag.setVisibility(View.VISIBLE);
		
		as.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				ivMusicFlag.clearAnimation();
				ivMusicFlag.setVisibility(View.GONE);
			}
		});
		
		TranslateAnimation ta = new TranslateAnimation(x,dm.widthPixels-70,y,40);
		ta.setDuration(500);
		
		AlphaAnimation aa = new AlphaAnimation(1,0);
		aa.setDuration(500);
		
		as.addAnimation(ta);
		as.addAnimation(aa);
		
		ivMusicFlag.setAnimation(as);
	}
	
	public void removeSong(Song song){
		boolean found = false;
		Song s = null;
		for(Iterator<Song> it = currentList.iterator();it.hasNext();){
			s = it.next();
			if(s.getName().equals(song.getName()) && s.getSinger().getName().equals(song.getSinger().getName())){
				found = true;
				break;
			}
		}
		
		if(found && s!=null){
			currentList.remove(s);
		}
	}
	
	public void clearMyList(){
		currentList = new ArrayList<Song>();
	}

	public BaseFragment getCurrentFragment() {
		return currentFragment;
	}

	public void setCurrentFragment(BaseFragment currentFragment) {
		this.currentFragment = currentFragment;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Fragment管理
		fm = getSupportFragmentManager();
		fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
			@Override
			public void onBackStackChanged() {
				if(fm.getBackStackEntryCount()==0){
					showPinYinSearch(View.GONE);
				}
			}
		});
		
		initContentView();
		initViews();
		
		initBaiduLoc();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void initContentView() {
		setContentView(R.layout.main);
	}

	public void initViews() {
		application = (GlobalApplication) getApplication();
		tabHost = (TabHost)this.findViewById(android.R.id.tabhost);
		
		application.tabHost = tabHost;
		GlobalApplication.activity = this;
		
		//初始化Tab
		initTab();
		//初始化拼音搜索
		initPinYin();
		//显示首页
		//加载我的列表
		mySongList= application.loadMyAlbums();
		if(mySongList.size()>0){
			this.setCurrentList(mySongList.get(0).getSongList());
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(fm.getBackStackEntryCount()==0){
				CustomDialog dialog = DialogUtil.showCustomDialog(this,"确定要退出了么？", 
						this.getTabHost(), Gravity.BOTTOM);
				dialog.setOnOkClickListener(new CustomDialog.OkClickListener() {
					@Override
					public void onClick(View v) {
						Log.i(Constant.DIANBA,"exit....");
						System.exit(0);
					}
				});
			}
			return true;
		}
		return false;
	}

	//初始化TAB
	private void initTab(){
		tabHost.setup();
		tabHost.setOnTabChangedListener(addTabChangeListener());
		tabHost.setCurrentTab(CURRENT_TAB);
		//初始化图标
		LinearLayout tabGroup= (LinearLayout)tabHost.findViewById(R.id.tabGroup);
		TabWidget tw = (TabWidget)tabGroup.findViewById(android.R.id.tabs);
		tabIndicator1 =(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw,false);
		setIconAndTitle(tabIndicator1,R.drawable.selector_search,"点歌");
		tabIndicator2 =(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw,false);
		setIconAndTitle(tabIndicator2,R.drawable.selector_my,"点歌单");
		tabIndicator3 =(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw,false);
		setIconAndTitle(tabIndicator3,R.drawable.selector_user_center,"我");
		tabIndicator4 =(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw,false);
		setIconAndTitle(tabIndicator4,R.drawable.selector_ktv,"周边");
		tabIndicator5 =(RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw,false);
		setIconAndTitle(tabIndicator5,R.drawable.selector_more,"更多");
		//添加Tab
		tabHost.addTab(tabHost.newTabSpec(Constant.TAG_HOME)
				.setIndicator(tabIndicator1)
				.setContent(new DummyTabContent(getBaseContext())));
		tabHost.addTab(tabHost.newTabSpec(Constant.TAG_MY)
				.setIndicator(tabIndicator2)
				.setContent(new DummyTabContent(getBaseContext())));
		tabHost.addTab(tabHost.newTabSpec(Constant.TAG_USER_CENTER)
				.setIndicator(tabIndicator3)
				.setContent(new DummyTabContent(getBaseContext())));
		tabHost.addTab(tabHost.newTabSpec(Constant.TAG_KTV)
				.setIndicator(tabIndicator4)
				.setContent(new DummyTabContent(getBaseContext())));
		tabHost.addTab(tabHost.newTabSpec(Constant.TAG_MORE)
				.setIndicator(tabIndicator5)
				.setContent(new DummyTabContent(getBaseContext())));
		
		
	}
	
	/*
	 * 设置TAB的图标和标题
	 */
	private void setIconAndTitle(RelativeLayout tabIndicator,int iconId,String title){
		tabIndicator.findViewById(R.id.icon).setBackgroundResource(iconId);;
		((TextView)tabIndicator.findViewById(R.id.title)).setText(title);
	}
	
	/*
	 * Tab Change事件
	 */
	private TabHost.OnTabChangeListener addTabChangeListener(){
		return new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				//隐藏拼音搜索
				showPinYinSearch(View.GONE);
				
				ft = fm.beginTransaction();
				
				ft.setCustomAnimations(R.anim.zoomin_fragment,R.anim.zoomout_fragment);
				//先把所有的Fragment隐藏起来
				hideAllFragment();
				
				if(tabId.equalsIgnoreCase(Constant.TAG_HOME)){
					homeFragment = showFragment(0,tabId,homeFragment,"com.yotoodesign.dianba.fragment.HomeFragment");
				}else if(tabId.equalsIgnoreCase(Constant.TAG_MY)){
					//显示点歌数据
					if(myFragment!=null && ((MyFragment)myFragment).getMySongAdapter()!=null){
						((MyFragment)myFragment).getMySongAdapter().setSongList(getCurrentList());
						((MyFragment)myFragment).getMySongAdapter().notifyDataSetChanged();
					}
					myFragment = showFragment(1,tabId,myFragment,"com.yotoodesign.dianba.fragment.MyFragment");
				}else if(tabId.equalsIgnoreCase(Constant.TAG_USER_CENTER)){
					userCenterFragment = showFragment(2,tabId,userCenterFragment,"com.yotoodesign.dianba.fragment.UserCenterFragment");
				}else if(tabId.equalsIgnoreCase(Constant.TAG_KTV)){
					ktvFragment = showFragment(3,tabId,ktvFragment,"com.yotoodesign.dianba.fragment.KtvFragment");
				}else if(tabId.equalsIgnoreCase(Constant.TAG_MORE)){
					moreFragment = showFragment(4,tabId,moreFragment,"com.yotoodesign.dianba.fragment.MoreFragment");
				}
				
				ft.commit();
			}
		};
	}
	
	/*
	 * 显示我的点歌单
	 */
	public void showMyFragment(){
		tabHost.setCurrentTab(1);
	}
	
	/*
	 * 隐藏Fragment
	 */
	private void hideAllFragment(){
		if(homeFragment!=null) ft.hide(homeFragment);
		if(myFragment!=null) ft.hide(myFragment);
		if(userCenterFragment!=null) ft.hide(userCenterFragment);
		if(ktvFragment!=null) ft.hide(ktvFragment);
		if(moreFragment!=null) ft.hide(moreFragment);
		
		singerFragment = (SingerFragment)fm.findFragmentByTag(Constant.TAG_SINGER);
		singerSongFragment = (SingerSongFragment)fm.findFragmentByTag(Constant.TAG_SINGER_SONG);
		ktvDetailFragment = (KtvDetailFragment)fm.findFragmentByTag(Constant.TAG_KTV_DETAIL);
		feedbackFragment = (FeedbackFragment)fm.findFragmentByTag(Constant.TAG_FEEDBACK);
		aboutFragment = (AboutFragment)fm.findFragmentByTag(Constant.TAG_ABOUT);
		
		if(singerFragment!=null) ft.detach(singerFragment);
		if(singerSongFragment!=null) ft.detach(singerSongFragment);
		if(ktvDetailFragment!=null) ft.detach(ktvDetailFragment);
		if(feedbackFragment!=null) ft.detach(feedbackFragment);
		if(aboutFragment!=null) ft.detach(aboutFragment);
		
	}
	
	//显示指定的Fragment
	private BaseFragment showFragment(int index,String tabId,BaseFragment fragment,String className){
		if(fragment==null){
			try {
				//实例化Fragment
				fragment = (BaseFragment)Fragment.instantiate(this, className);
				ft.add(R.id.realtabcontent,fragment, tabId);
			} catch (Exception e) {
				Log.i(Constant.DIANBA,"instantiate "+className+" Error!");
			}						
		}else{
			ft.show(fragment);
		}
		
		CURRENT_TAB = index;
		currentFragment = fragment;
		return fragment;
	}
	
	/**
	 * 退出前的确认
	 */
	private void exitConfirm(){
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setTitle("提示").setMessage("确认要退出"+getResources().getString(R.string.app_name)+"？")
			.setIcon(R.drawable.ic_launcher)
			.setPositiveButton("确认", new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					System.exit(0);
				}
			})
			.setNegativeButton("取消", new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
				
			})
			.create().show();
	}
	
	/*
	 * 初始化拼音搜索
	 */
	private void initPinYin(){
		LinearLayout letters1 = (LinearLayout)findViewById(R.id.letters1);
		for(int i = 0;i<letters1.getChildCount();i++){
			Button but = (Button)letters1.getChildAt(i);
			but.setOnTouchListener(addTouchListener());
		}
		
		LinearLayout letters2 = (LinearLayout)findViewById(R.id.letters2);
		for(int i = 0;i<letters2.getChildCount();i++){
			Button but = (Button)letters2.getChildAt(i);
			but.setOnTouchListener(addTouchListener());
		}
		
		LinearLayout letters3 = (LinearLayout)findViewById(R.id.letters3);
		for(int i = 0;i<letters3.getChildCount();i++){
			Button but = (Button)letters3.getChildAt(i);
			but.setOnTouchListener(addTouchListener());
		}

		ImageButton remove = (ImageButton)findViewById(R.id.remove);
		remove.setOnClickListener(backHandler());
		
	}
	
	/*
	 * 拼音搜索按钮事件
	 */
	private View.OnClickListener pinyinChanger(){
		final TextView tvInputed = (TextView)findViewById(R.id.tvInputed);
		return new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				String label = ((Button)v).getText().toString();
				tvInputed.setText(tvInputed.getText()+label);
			}
			
		};
	}
	
	/*
	 * 回退删除事件
	 */
	private View.OnClickListener backHandler(){
		final TextView tvInputed = (TextView)findViewById(R.id.tvInputed);
		return new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				String s = tvInputed.getText().toString();
				if(s.length()>0){
					s = s.substring(0, s.length()-1);
					tvInputed.setText(s);
					filterHandler(currentFragment,tvInputed.getText().toString());
				}
			}
		};
	}
	
	/*
	 * 按钮按下与抬起时，显示字母预览
	 */
	private OnTouchListener addTouchListener(){
		return new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				String label = ((Button)v).getText().toString();
				RelativeLayout selectedLetter =(RelativeLayout)findViewById(R.id.selectedLetter);
				TextView tvSelected = (TextView)findViewById(R.id.tvSelected);
				int[] location = new int[2];
				v.getLocationInWindow(location);
				
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
						80, RelativeLayout.LayoutParams.WRAP_CONTENT);
				lp.addRule(RelativeLayout.ABOVE,v.getId());
				lp.addRule(RelativeLayout.ALIGN_LEFT,v.getId());
				selectedLetter.setLayoutParams(lp);
				
				switch(event.getAction()){
				case MotionEvent.ACTION_DOWN:
					selectedLetter.setVisibility(View.VISIBLE);
					tvSelected.setText(label);
					break;
				case MotionEvent.ACTION_UP:
					selectedLetter.setVisibility(View.GONE);
					TextView tvInputed = (TextView)findViewById(R.id.tvInputed);
					tvInputed.setText(tvInputed.getText()+label);
					//根据输入的字母过滤数据
					filterHandler(currentFragment,tvInputed.getText().toString());
					
					break;
				}
				return false;
			}
		};
	}
	/*
	 * 显示拼音搜索模块
	 */
	public void showPinYinSearch(int visibility){
		int x1=0,x2=0,y1=0,y2=0 ;
		
		final LinearLayout pinyin =(LinearLayout)findViewById(R.id.pinyin);
		pinyin.setVisibility(visibility);
		
//		final DisplayMetrics dm = new DisplayMetrics();
//		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
//		x1 = 0;
//		y1 = dm.heightPixels;
//		x2 = 0;
//		y2 = dm.heightPixels-250;
//		Log.i(Constant.DIANBA,">>>>>>>>>>>"+x1+","+x2+","+y1+","+y2);
//		final int finaly = y2;
//		if(visibility == View.VISIBLE){
//			TranslateAnimation translate = new TranslateAnimation(x1,x2,y1,y2);
//			translate.setAnimationListener(new AnimationListener() {
//				@Override
//				public void onAnimationStart(Animation animation) {
//				}
//				@Override
//				public void onAnimationRepeat(Animation animation) {
//				}
//				@Override
//				public void onAnimationEnd(Animation animation) {
//					pinyin.clearAnimation();
//				}
//			});
//			translate.setDuration(300);
//			translate.setFillAfter(true);
//			pinyin.startAnimation(translate);
//		}
	}
	/*
	 * 清除拼音输入
	 */
	public void clearPinYin(){
		TextView tvInputed =(TextView)findViewById(R.id.tvInputed);
		tvInputed.setText("");
	}
	/*
	 * 设置拼音
	 */
	public void setPinYin(String pinyin){
		TextView tvInputed =(TextView)findViewById(R.id.tvInputed);
		tvInputed.setText(pinyin);
	}
	/*
	 * 获取拼音
	 */
	public String getPinYin(){
		TextView tvInputed =(TextView)findViewById(R.id.tvInputed);
		return tvInputed.getText().toString();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	/*
	 * 根据拼音过滤数据
	 */
	private void filterHandler(BaseFragment fragment,String pinyin){
		//根据输入的字母过滤数据
		ArrayList result = DataUtils.filterHandler(fragment.getSourceList(),pinyin);
		//更新对应fragment中的视图数据
		fragment.setDataList(result);
		fragment.updateListView();
	}
	
	/*
	 * 返回到首页
	 */
	public void goHome(){
		ft = fm.beginTransaction();
		ft.attach(homeFragment);
		ft.commit();
		
		currentFragment = homeFragment;
		tabHost.setCurrentTab(0);
	}
	
	
	/*
	 * 显示TAB
	 */
	public void showTab(boolean visible){
		tabHost.getTabWidget().setVisibility(visible?View.VISIBLE:View.GONE);
	}
	
	/*
	 * 初始化百度定位
	 * http://api.map.baidu.com/place/search?&query=KTV&location=31.830460,117.312726&radius=2000&output=xml&key=37492c0ee6f924cb5e934fa08c6b1676
	 */
	private void initBaiduLoc(){
		mLocClient = ((GlobalApplication)getApplication()).mLocationClient;
		setLocationOption();
	}
	
	
	//设置相关参数
	private void setLocationOption(){
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");//返回的定位结果包含地址信息
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
		option.setServiceName("com.yotoodesign.location");//com.baidu.location.service_v2.9
		option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
		option.disableCache(true);//禁止启用缓存定位
		option.setPoiNumber(5);	//最多返回POI个数	
		option.setPoiDistance(1000); //poi查询距离		
		option.setPoiExtraInfo(true); //是否需要POI的电话和地址等详细信息		
		option.setPriority(LocationClientOption.GpsFirst); //Gps优先,网络优先：NetWorkFirst
		
		mLocClient.setLocOption(option);
	}
	
	@Override
	public void onDestroy() {
		mLocClient.stop();
		super.onDestroy();
	}

	public ArrayList<Album> getMySongList() {
		return mySongList;
	}

	public void setMySongList(ArrayList<Album> mySongList) {
		this.mySongList = mySongList;
	}

	public TabHost getTabHost() {
		return tabHost;
	}

	public void setTabHost(TabHost tabHost) {
		this.tabHost = tabHost;
	}

	public BaseFragment getUserCenterFragment() {
		return userCenterFragment;
	}

	public void setUserCenterFragment(BaseFragment userCenterFragment) {
		this.userCenterFragment = userCenterFragment;
	}
	
	


}


